/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 14:11:35
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-08-30 20:53:36
 * @FilePath: \keep_motion_api\models\menu\role.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 角色模型
const roleSchema = new Schema({
  code: { type: String, required: true, unique: true },
  name: { type: String, required: true },
  description: String,
  permissions: [],
  menus: [{
    type: Schema.Types.ObjectId,
    ref: 'Menu'
  }],
});

roleSchema.statics.getRole = async function (name = '', code = '', offset, limit) {
  try {
    const query = {};
    if (code) {
      const escapedCode = escapeRegex(code);
      query.code = { $regex: escapedCode, $options: 'i' };
    }
    if (name) {
      const escapedName = escapeRegex(name);
      query.name = { $regex: escapedName, $options: 'i' };
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.find(query)
      .skip(Number(offset))
      .limit(Number(limit));
    return { rows, total };
  } catch (error) {
    throw error;
  }
}

roleSchema.statics.createRole = async function (name, code, description) {
  try {
    const role = await this.create({ name, code, description });
    return role;
  } catch (error) {
    throw error;
  }
}
roleSchema.statics.deleteRole = async function (id) {
  try {
    const role = await this.findByIdAndDelete(id);
    return role;
  } catch (error) {
    throw error;
  }
}
roleSchema.statics.updateRolePermission = async function (id, permissionIds) {
  try {
    const paramsArr = permissionIds.map(item => item.split(':')[0]);
    const { Permission } = require('./');
    const permissions = await Permission.find({ _id: { $in: paramsArr } });
    const menus = [...new Set(permissions.map(perm => perm.menu_item))];
    const role = await this.findByIdAndUpdate(id, { permissions: permissionIds, menus: menus },{ new: true });
    return role;
  } catch (error) {
    throw error;
  }
}


module.exports = mongoose.model('Role', roleSchema);
